package client

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

type client interface {
}

type clientProperty struct {
	Conn *net.TCPConn
	Name string
}

func MakeClient() clientProperty {
	tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:9999")
	if err != nil {
		fmt.Println("net.ResolveTCPAddr error:", err)
		return clientProperty{}
	}

	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		return clientProperty{}
	}

	return clientProperty{
		Conn: conn,
		Name: conn.RemoteAddr().String(),
	}
}

func (c *clientProperty) RunClient() {
	defer c.Conn.Close()

	fmt.Println("connected")

	go c.onMessageReceived() //读取服务端广播的信息

	for {
		// 自己的信息
		var data string
		fmt.Scan("%s", &data)

		if data == "quit" {
			break
		}

		b := []byte(data)

		c.Conn.Write(b)

	}

}

func (c *clientProperty) onMessageReceived() {
	reader := bufio.NewReader(c.Conn)

	for {
		msg, err := reader.ReadString('\n')
		fmt.Println(msg)
		if err != nil {
			fmt.Println("err:", err)
			os.Exit(1) //服务端错误的时候，就将整个客户端关掉
		}
	}
}
